import { getPlantQuarantine } from '@/api/agriculture.ts';
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';

export const useConsultationStore = defineStore('ConsultationStore', () => {
  // 定义状态
  const isLoadingLaw = ref<boolean>(false);
  const lawConsultationData = ref<any[]>([]);

  // 获取政策法规数据
  const getPolicyList = async () => {
    isLoadingLaw.value = true;
    // 修改请求参数格式
    const req = {
      pageNo: 1,
      pageSize: 6,
    };
    try {
      const res = await getPlantQuarantine(req);
      const { data } = res;
      // 对获取到的数据按照时间属性进行排序
      const sortedData = data.sort((a, b) => {
        const timeA = new Date(a.attributes.time).getTime();
        const timeB = new Date(b.attributes.time).getTime();
        // 降序排序，最新的时间在前
        return timeB - timeA;
      });
      // 处理排序后的数据
      lawConsultationData.value = sortedData.map((item) => ({
        id: item.id,
        title: item.attributes.name,
        date: item.attributes.time,
        url: item.attributes.url,
      }));
    } catch (error) {
      console.error('Error fetching data:', error);
    } finally {
      isLoadingLaw.value = false; // 请求完成后结束加载
    }
  };

  // 计算属性，用于获取政策法规数据
  const getLawConsultationData = computed(() => {
    return lawConsultationData.value;
  });

  // 计算属性，用于获取加载状态
  const getLawLoading = computed(() => {
    return isLoadingLaw.value;
  });

  return {
    getPolicyList,
    getLawConsultationData,
    getLawLoading,
  };
});
